package javango.forms.widgets;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javango.forms.fields.ChoiceField;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SelectMultipleWidget extends SelectWidget {

	private final static Log log = LogFactory.getLog(SelectMultipleWidget.class);

	public SelectMultipleWidget() {
		super();
		this.getAttrs().put("multiple", "multiple");
	}

	public SelectMultipleWidget(Map<String, Object> attrs, ChoiceField field) {
		super(attrs, field);
		this.getAttrs().put("multiple", "multiple");
	}
	
	public String render(String name, Object value, Map<String, Object> attrs) {
		Map<String, Object> finalAttrs = buildAttrs(attrs);
		finalAttrs.put("name", name);
		
		if (finalAttrs.containsKey("id")) {
			finalAttrs.put("id", String.format((String)finalAttrs.get("id"), name));
		}
		
		StringBuilder b = new StringBuilder("<select");
		Util.flatatt(finalAttrs, b);
		b.append(">");
				
		String optionHtml = "<option value=\"%s\" %s>%s</option>"; // value, selected, display
//		
//		if (value == null) {
//			b.append(String.format(optionHtml, "", "", "--"));
//		}
				
		List<String> values = new ArrayList<String>();
		if (value != null) {
			for (Object o : (Object[])value) {
				values.add(o.toString());
			}
		}
		
		for (Map.Entry<String, Object> entry : getMyChoices().entrySet() ) {
			String optionValue = entry.getKey();
			String selected = value == null ? "" : values.contains(optionValue) ? "selected=\"selected\"" : "";
			log.debug("optionValue : '" + optionValue + "'; value : '" + value + "'");
			b.append(String.format(optionHtml, optionValue.toString(), selected, entry.getValue()));
		}
		b.append("</select>");
		return b.toString();
	}

}
